// 网络请求相关
export default {
  /**
   * 基础HTTP请求
   * @param String url 访问地址
   * @param Object data
   * @param String method
   */
  http(url, data = {}, method = 'POST') {
    return new Promise((resolve, reject) => {
      uni.showLoading({
        title: '请稍等...',
      });
      uni.request({
        url: ~url.indexOf('http') ? url : this.HTTP_URL + url,
        method,
        data: JSON.stringify(data),
        header: {
          'Content-Type': 'text/plain',
        },
        success: (res) => {
          uni.hideLoading();
          // console.info('HTTP请求', url, data, res)
          if (res.statusCode !== 200) {
            // 请求报错
            this.toast('服务器正忙，请稍后再试');
          } else if (res.data.code == 200 || res.data.code == 201) {
            // 需要登录
            this.toast('未登录');
            // this.login(() => {
            // 	this.request(url, data, success, method, block)
            // })
          } else if (res.data.code != 0) {
            // 操作失败
            this.toast(res.data.msg);
          } else {
            // 操作成功
            resolve(res.data);
          }
        },
      });
    });
  },

  /**
   *openid 是用户的标识，支付需要用到openid
   */
  async getOpenId() {
    // code是登录的凭证
    var code = this.getQueryString('code');
    if (!code) {
      // 微信网页授权
      location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid
				=${this.GZH_APPID}&
				redirect_uri=${encodeURIComponent(location.href)}
				&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
    } else {
      // code 获得 openid
      const res = await this.http('user/getOpenId', {
        code,
      });

      this.setData('openid', res.data.openid);
    }
  },
};
